import { createStore } from 'vuex'
import { getToken, setToken } from '@/utils/auth'
import { get, post } from '@/utils/request'
export default createStore({
  state: {
    token: getToken(),
    userInfo: null
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      setToken(token)
    },
    SET_INFO: (state, info) => {
      state.userInfo = info
    }
  },
  actions: {
    getInfo({ commit }) {
      return new Promise((resolve, reject) => {
        get('/user/get_userinfo')
          .then((res) => {
            commit('SET_INFO', res.data)
            resolve()
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    login({ commit }, data) {
      return new Promise((resolve, reject) => {
        post('/user/login', data)
          .then((res) => {
            commit('SET_TOKEN', res.data.token)
            resolve()
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    logout({ commit }) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', '')
        commit('SET_INFO', '')
        resolve()
      })
    }
  },
  modules: {}
})
